package com.sdk.cachesdk.service;

import com.github.benmanes.caffeine.cache.Cache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service("caffine")
public class CaffineCacheServiceImpl implements CacheService {

    @Autowired
    private Cache<String, Object> cache;

    @Override
    public void set(String key, Object value) {
        cache.put(key, value);
    }

    @Override
    public void set(String key, Object value, long ttl) {
        cache.put(key, value);
        // 如果需要为每个键单独设置 TTL，可以在插入时记录过期时间并定期清理
    }

    @Override
    public <T> T get(String key, Class<T> type) {
        return type.cast(cache.getIfPresent(key));
    }

    @Override
    public boolean delete(String key) {
        cache.invalidate(key);
        return true;
    }

    @Override
    public boolean hasKey(String key) {
        return cache.getIfPresent(key) != null;
    }

    @Override
    public boolean expire(String key, long ttl) {
        if (cache.getIfPresent(key) == null) {
            return false;
        }
        // 如果需要动态调整过期时间，可以记录每个键的过期时间并在后台任务中清理
        return true;
    }
}